function loginCheck(){
   
    const sessionInsName=document.getElementById('sessionInsName').textContent;
    const sessionInsId=document.getElementById('sessionInsId').textContent;
    const insIsLogin=localStorage.getItem('isLogin')
    console.log(window.location.href);
    if(insIsLogin!=='true'){
        window.location.href='/';
    }
    if(sessionInsName.includes('None')){
        localStorage.removeItem('isLogin');
        window.location.href='/';
    }
    
    fetch('/check_login',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
            },
        body:JSON.stringify({'user_id':sessionInsId})                
        })
    .then(response=>response.json())
    .then(data=>{
        if(data.res==='failed'){
            console.log('ins id is not valid.')
            localStorage.removeItem('isLogin');
            window.location.href='/';
        }
    }
    )
    .catch(error=>{
        console.log(error);
    });   

    getDataBaseType();

    return 'isLogin'
   
}

function addGoLastPageBtn(){
            // 获取返回首页按钮
            const goIndexBtn = document.getElementById('goIndex');
            
            // 创建返回上级按钮
            const goBackButton = document.createElement('button');
            goBackButton.textContent = '返回上级';
            goBackButton.className = 'session-name';
            goBackButton.style.margin = '0';
            goBackButton.style.padding = '2px 5px';
            goBackButton.style.fontSize = '8px';
            goBackButton.style.height = '20px';
            goBackButton.style.width = '60px';
            goBackButton.style.lineHeight = '1';
            
            // 添加点击事件
            goBackButton.addEventListener('click', function() {
                window.history.back(); // 或 window.history.go(-1);
            });
            
            // 在返回首页按钮后插入返回上级按钮
            goIndexBtn.insertAdjacentElement('afterend', goBackButton);
        }

function logout(){
    localStorage.removeItem('isLogin');
    window.location.href='/logout';
}

function goIndex(){
    window.location.href='/main';
}

function hideInsSelectBlockAndGetInsInfo(id){
    
    const sessionInsId=document.getElementById('sessionInsId').textContent;
    const sessionInsName=document.getElementById('sessionInsName').textContent;
    const sessionLoggedIn=document.getElementById('sessionLoggedIn').textContent;
    const sessionRoleBlock=document.getElementById('sessionInsRole');
    const showRole=document.getElementById('showRole');

    const sessionInsRole=sessionRoleBlock.textContent;
    if(id){
        const insSelectBlock=document.getElementById(id);
        if(sessionInsRole==='admin'){
            //关掉这句，才能保证form-row的css正确显示
            // insSelectBlock.style.display='block';
            insSelectBlock.classList.add('form-row');            
            showRole.innerText='管理员'
        }else if(sessionInsRole==='ins'){
            insSelectBlock.style.display='none';
            showRole.innerText='教练'
        }
    }else{
        if(sessionInsRole==='admin'){   
            showRole.innerText='管理员'
        }else if(sessionInsRole==='ins'){ 
            showRole.innerText='教练'
        }
    }
    sessionRoleBlock.style.display='none';
    return ({'sessionInsId':sessionInsId,'sessionInsName':sessionInsName,'sessionInsRole':sessionInsRole,'sessionLoggedIn':sessionLoggedIn})
}


function generateInsList(insData,selectId){
    const insSelect=document.getElementById(selectId);
    insData.forEach(ins=>{
        const option=document.createElement('option')
        option.value=ins.slice(0,8);
        option.text=ins.slice(8,);
        insSelect.appendChild(option);                    
        });
}

function getDataBaseType(){
    const dataBaseType=document.getElementById('dataBaseType');
    dataBaseType.innerHTML='';
    fetch('/check_database_type')
    .then(response=>response.json())
    .then(data=>{
        // console.log('databae type:',data);
        if(data['data_base_type']==='测试机'){
            dataBaseType.innerHTML=`<span style="color:red;">${data['data_base_type']} ${data['data_base_name']}</span>`;
        }else{
            dataBaseType.innerHTML=''
        }
    })
}


function currentLocalTime(){   
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth()+1;
    const date = now.getDate();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds(); 
    const fmtTime=`${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
    return fmtTime

}

function selectToday(id,format){
    const today = new Date();
    let formattedDate;
    // 将日期格式化为 yyyy-mm-dd 的形式
    if(format==='dateTime'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}T${hours}:${minutes}`;
    }else if(format==='date'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}`
    }else if(format==='month'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}`
    }

    // 将日期设置为输入框的默认值
    document.getElementById(id).value = formattedDate;
}

function dateToStringGmt(dateInput0,format){
    // const dateInput = dateInput0.toLocaleString('en-US', { timeZone: 'GMT' });
    const gmtDate=new Date(dateInput0)
    const timeZoneOffset=gmtDate.getTimezoneOffset();
    // console.log(timeZoneOffset)
    const dateInput=new Date(gmtDate.getTime()+(timeZoneOffset*60*1000))
    // const dateInput = gmtDate.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
     
    // const dateInput = new Date(Date.UTC(parseInt(dateParts[2]), month, parseInt(dateParts[0]), parseInt(dateParts[3]), parseInt(dateParts[4]), parseInt(dateParts[5])));
    // console.log('new time:',dateInput)
    const today = new Date(dateInput);
    let formattedDate;
    // 将日期格式化为 yyyy-mm-dd 的形式
    if(format==='dateTime'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}T${hours}:${minutes}`;
    }else if(format==='date'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}`
    }else if(format==='time'){
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${hours}:${minutes}`;
    }else if(format==='dateChn'){
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            // const hours = String(today.getHours()).padStart(2, '0');
            // const minutes = String(today.getMinutes()).padStart(2, '0');
            formattedDate = `${year}年${month}月${day}日`
    }else if(format==='dateHour'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day} ${hours}:00`
    }
    else if(format==='monthDate'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${month}-${day}`
    }else if(format==='dateDot'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}.${month}.${day}`
    }else if(format==='dateShortSlash'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${String(year).slice(-2)}/${month}/${day}`
    } 
    return formattedDate;
}

function hasNonZeroDecimal(number) {
    const decimalPart = (number % 1).toString(); // 获取小数部分
    const decimalDigits = decimalPart.split('.')[1]; // 切分小数部分
  
    if (decimalDigits) {
      return decimalDigits.split('').some(digit => digit !== '0'); // 判断是否有非零数字
    }
  
    return false; // 无小数部分，返回false
  }


function dateToString(dateInput,format){
    const today = new Date(dateInput);
    let formattedDate;
    // 将日期格式化为 yyyy-mm-dd 的形式
    if(format==='dateTime'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}T${hours}:${minutes}`;
    }else if(format==='date'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}`
    }else if(format==='time'){
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${hours}:${minutes}`;
    }else if(format==='dateChn'){
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            // const hours = String(today.getHours()).padStart(2, '0');
            // const minutes = String(today.getMinutes()).padStart(2, '0');
            formattedDate = `${year}年${month}月${day}日`
    }else if(format==='digit8'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}${month}${day}`
    }else if(format==='digit14'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        const seconds = String(today.getSeconds()).padStart(2, '0');
        formattedDate = `${year}${month}${day}${hours}${minutes}${seconds}`
    }else if(format==='dateDot'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${year}.${month}.${day}`
    }else if(format==='monthDayDot'){
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const hours = String(today.getHours()).padStart(2, '0');
        // const hours = String(today.getHours()).padStart(2, '0');
        // const minutes = String(today.getMinutes()).padStart(2, '0');
        formattedDate = `${month}.${day}`
    }
    return formattedDate;
}

function calculateDate(dateInput,days){
    const currentDate = new Date(dateInput);

    // 获取当前日期中的日期部分
    const day = currentDate.getDate();

    // 将日期部分设置为当前日期加上30天的日期
    currentDate.setDate(day + days);

    // 将日期转换为字符串并输出
    const formattedDate = currentDate.toLocaleDateString();
    
    return formattedDate;
}

function selectDate(dateInput,id,format){
  const today = new Date(dateInput);
  let formattedDate;
  // 将日期格式化为 yyyy-mm-dd 的形式
  if(format==='dateTime'){
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      const hours = String(today.getHours()).padStart(2, '0');
      const minutes = String(today.getMinutes()).padStart(2, '0');
      formattedDate = `${year}-${month}-${day}T${hours}:${minutes}`;
  }else if(format==='date'){
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      // const hours = String(today.getHours()).padStart(2, '0');
      // const minutes = String(today.getMinutes()).padStart(2, '0');
      formattedDate = `${year}-${month}-${day}`
  }

  // 将日期设置为输入框的默认值
  document.getElementById(id).value = formattedDate;
}

function dateFormat(currentDate,fmt){
    function pad(number) {
        return number < 10 ? '0' + number : String(number);
      }

    let formattedDate;
    if(fmt==='date'){
        var year = currentDate.getFullYear();
        var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
        var day = ("0" + currentDate.getDate()).slice(-2);
        formattedDate = year + "-" + month + "-" + day;
    }else if(fmt==='time'){
        const hours = String(today.getHours()).padStart(2, '0');
        const minutes = String(today.getMinutes()).padStart(2, '0');
        const seconds = currentDate.getSeconds();
        // const formattedDatetime = `${year}-${month}-${day}T${hours}:${minutes}`;
        formattedDate = `${hours}:${minutes}:${seconds}`;
    }else if(fmt==='date_time_14_digits'){
        const year = currentDate.getFullYear();
        const month = pad(currentDate.getMonth() + 1); // 月份是从0开始的
        const day = pad(currentDate.getDate());
        const hours = pad(currentDate.getHours());
        const minutes = pad(currentDate.getMinutes());
        const seconds = pad(currentDate.getSeconds());

        formattedDate= year + month + day + hours + minutes + seconds;
        // formattedDate= 
    }
    
    // 拼接日期字符串，例如：YYYY-MM-
    if (formattedDate.includes('NaN')){
        return '-';
    }else{
        return formattedDate;
    }              
}

// 比较日期相差的天数
function compareDatesDiffDays(date1,date2){
    // console.log(date1,date2)
    // 将日期字符串转换为 Date 对象
    const d1 = new Date(date1);
    const d2 = new Date(date2);

    // 计算两个日期之间的毫秒数差异
    const diffTime = Math.abs(d2 - d1);

    // 将毫秒数差异转换为天数
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    return diffDays;

}

// 比较日期相差的天数，绝对值，无正负
function compareDatesOnly(date1,date2){
    // console.log(date1,date2)
    // 将日期字符串转换为 Date 对象
    const d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
    const d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());

    // 计算两个日期之间的毫秒数差异
    const diffTime = Math.abs(d2 - d1);

    // 将毫秒数差异转换为天数
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    return diffDays;

}

// 比较日期相差的天数，有正负
function compareDatesOnly2(date1,date2){
    // console.log(date1,date2)
    // 将日期字符串转换为 Date 对象
    const d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
    const d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());

    // 计算两个日期之间的毫秒数差异
    const diffTime =d2 - d1;

    // 将毫秒数差异转换为天数
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    return diffDays;

}

  // 显示自定义模态框
  function showCustomModal() {
    const modal = document.getElementById('customModal');
    modal.style.display = 'block';
  }

  // 隐藏自定义模态框
  function hideCustomModal() {
    const modal = document.getElementById('customModal');
    modal.style.display = 'none';
  }

  // 确认或取消操作
  function confirmAction(isConfirmed) {
    if (isConfirmed) {
      // 执行确认操作
      console.log('确认');
    } else {
      // 执行取消操作
      console.log('取消');
    }

    // 隐藏模态框
    hideCustomModal();
  }


  class customButton{
    constructor(id='customModel'){
        this.className='customButton';
        this.id=id;
    }

      // 显示自定义模态框
    showCustomModal() {
        const modal = document.getElementById(this.id);
        modal.style.display = 'block';
    }

    // 隐藏自定义模态框
    hideCustomModal() {
        const modal = document.getElementById(this.id);
        modal.style.display = 'none';
    }

    // 确认或取消操作
    confirmAction(isConfirmed) {
        if (isConfirmed) {
        // 执行确认操作
        console.log('确认');
        } else {
        // 执行取消操作
        console.log('取消');
        }

        // 隐藏模态框
        hideCustomModal(this.id);
    }
  }

function sortByOrder(arr, order) {
    var filteredArr = arr.filter(function(item) {
      return order.includes(item);
    });
  
    filteredArr.sort(function(a, b) {
      return order.indexOf(a) - order.indexOf(b);
    });
  
    if (arr.length >= order.length) {
      var additionalItems = arr.filter(function(item) {
        return !order.includes(item);
      });
      filteredArr = filteredArr.concat(additionalItems);
    }
  
    return filteredArr;
  }


  function toBeijingTimeString(date) {
    // 克隆日期对象，防止修改原始日期
    let bjDate = new Date(date.getTime());
    // 增加8小时
    bjDate.setHours(bjDate.getHours() + 8);
    // 格式化为 YYYY-MM-DD
    return bjDate.toISOString().split('T')[0];
}


function toBeijingTime(date) {
    // 克隆日期对象，防止修改原始日期
    let bjDate = new Date(date.getTime());
    // 增加8小时
    bjDate.setHours(bjDate.getHours() + 8);
    // 格式化为 YYYY-MM-DD
    return bjDate
}